/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 版本: 苏州公安统一用户管理平台1.0
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名:LogRecordInterceptor.java
 * <p>
 * 类产生时间: 2012-9-17 下午4:52:49
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 苏州公安统一用户管理平台
 * <p>
 * 所在部门: 电信/国土——技术二部
 * <p>
 * <p>
 */
package com.oceansoft.core.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.oceansoft.core.common.constant.Constant;
import com.oceansoft.core.domain.SysOperLog;
import com.oceansoft.core.domain.SysUser;
import com.oceansoft.core.recorder.LogRecordEvent;

/**
 * 操作快照日志拦截
 * 
 * @author chenw
 * 
 */
public class LogRecordInterceptor implements HandlerInterceptor, ApplicationContextAware {
	private ApplicationContext ctx;

	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView view)
			throws Exception {
		Object obj = req.getSession().getAttribute(Constant.LOGIN_USER);
		if (null != obj) {
			SysUser user = (SysUser) obj;
			String _uri = req.getRequestURI().toLowerCase();
			boolean _isAjax = _uri.endsWith(".json") || _uri.endsWith(".xml") || _uri.endsWith("jsonx");
			Object _obj = null;
			if (null == view) {
				if (_isAjax) {
					_obj = req.getAttribute(Constant.LOG_RECORD);
				}
			} else {
				Map<String, Object> _model = view.getModel();
				if (null == _model) {
					return;
				}
				_obj = _model.get(Constant.LOG_RECORD);
			}
			if (null == _obj && view != null) {
				ModelMap _model2 = view.getModelMap();
				if (null == _model2) {
					return;
				}
				_obj = _model2.get(Constant.LOG_RECORD);
			}
			if (null != _obj) {
				SysOperLog _log = (SysOperLog) _obj;
				_log.setIp(req.getRemoteHost());
				_log.setUserid(user.getPoliceNum());
				_log.setUname(user.getName());
				_log.setDeptName(user.getDeptName());
				LogRecordEvent event = new LogRecordEvent(LogRecordInterceptor.this.ctx, _log);
				ctx.publishEvent(event);
			}
		}
	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
		return true;
	}

	@Override
	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		this.ctx = ctx;
	}
}
